<script setup lang="ts">
import { ref, computed } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import { addDialog } from "@/components/ReDialog";
import dialogForms, { type FormProps } from "./handle_pwd.vue";
import {
  PlusSearch,
  PlusDialogForm,
  type PlusColumn,
  type FieldValues
} from "plus-pro-components";
import { ElMessage } from "element-plus";
import { router } from "@/router";
import { setUser, setUserPwd } from "@/api/user";
import { getMenuByPath } from "@/router/utils";
import { deviceDetection } from "@pureadmin/utils";
const isMobile = deviceDetection();
console.log("isMobile", isMobile);
(async function getMenu() {
  try {
    const menu = await getMenuByPath();
    console.log("当前menu", menu);
  } catch (error) {
    console.log(error);
  }
})();
defineOptions({
  name: "UserManage"
});
import { useMenu } from "@/utils/power";
const power = useMenu([
  "info",
  "edit",
  "loginPwd",
  "payPwd",
  "userLevel",
  "setHhr"
]);

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "查询用户下级",
    width: 100,
    labelWidth: 120,
    prop: "pId",
    fieldProps: {
      controls: false
    },
    valueType: "input-number",
    tooltip: "请输入用户ID"
  },
  {
    label: "是否等级固定",
    prop: "levelAdmin",
    labelWidth: 120,
    valueType: "select",
    options: [
      {
        label: "否",
        value: 0,
        color: "red"
      },
      {
        label: "是",
        value: 1,
        color: "red"
      }
    ]
  },
  {
    label: "等级",
    prop: "level",
    hideInSearch: computed(() => !power.value.userLevel),
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "VIP1",
        value: 1
      },
      {
        label: "VIP2",
        value: 2
      },
      {
        label: "VIP3",
        value: 3
      },
      {
        label: "VIP4",
        value: 4
      },
      {
        label: "VIP5",
        value: 5
      },
      {
        label: "VIP6",
        value: 6
      },
      {
        label: "VIP7",
        value: 7
      }
    ]
  }
  // {
  //   label: "用户状态",
  //   prop: "status",
  //   valueType: "select",
  //   options: [
  //     {
  //       label: "启用",
  //       value: "normal"
  //     },
  //     {
  //       label: "禁用",
  //       value: "hidden"
  //     }
  //   ]
  // },
  // {
  //   label: "权重值",
  //   width: 200,
  //   prop: "weight",
  //   valueType: "input-number",
  //   tooltip: "请输入大于权重值的订单"
  // }
];

const searchValues = ref({ starrating: 0 });
const defaultSearchState = ref({ starrating: 0 });

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  onSizeChange,
  loadData,
  onKeywordChange,
  onCurrentChange
} = useColumns();
const columnsRef = computed(() => {
  if (
    // power.value.edit ||
    power.value.info ||
    power.value.loginPwd ||
    power.value.payPwd
  ) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});

const setHhr = async row => {
  const value = {
    userId: row.id,
    money: row.money,
    score: row.score,
    level: row.level,
    starrating: 1,
    status: row.status,
    levelAdmin: row.level_admin,
    showLevel: row.show_level,
    jtsfkg: row.jtsfkg,
    isWeight: 1
  };
  try {
    const res = await setUser(value);
    // formRef.value?.formInstance?.resetFields();
    ElMessage.success("设置成功");
  } catch (error) {
    console.log(error, "error");
  }
};

function detailClick(row) {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  router.push({ name: "UserDetail", query: { id: row.id } });
}

const rules = {};
const formColumns: PlusColumn[] = [
  {
    label: "余额",
    prop: "money",
    valueType: "input"
  },
  {
    label: "收益",
    prop: "score",
    valueType: "input"
  },
  {
    label: "等级",
    prop: "level",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "VIP1",
        value: 1
      },
      {
        label: "VIP2",
        value: 2
      },
      {
        label: "VIP3",
        value: 3
      },
      {
        label: "VIP4",
        value: 4
      },
      {
        label: "VIP5",
        value: 5
      },
      {
        label: "VIP6",
        value: 6
      },
      {
        label: "VIP7",
        value: 7
      }
    ]
  },
  {
    label: "显示等级",
    prop: "showLevel",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "VIP1",
        value: 1
      },
      {
        label: "VIP2",
        value: 2
      },
      {
        label: "VIP3",
        value: 3
      },
      {
        label: "VIP4",
        value: 4
      },
      {
        label: "VIP5",
        value: 5
      },
      {
        label: "VIP6",
        value: 6
      },
      {
        label: "VIP7",
        value: 7
      }
    ]
  },
  {
    label: "是否合伙人",
    prop: "starrating",
    valueType: "select",
    options: [
      {
        label: "普通用户",
        value: 0
      },
      {
        label: "合伙人",
        value: 1
      }
    ]
  },
  {
    label: "是否固定等级",
    prop: "levelAdmin",
    valueType: "select",
    options: [
      {
        label: "不固定",
        value: "0"
      },
      {
        label: "固定",
        value: "1"
      }
    ]
  },
  {
    label: "用户状态",
    prop: "status",
    valueType: "select",
    options: [
      {
        label: "启用",
        value: "normal"
      },
      {
        label: "禁用",
        value: "hidden"
      }
    ]
  },
  {
    label: "静态释放",
    prop: "jtsfkg",
    valueType: "select",
    options: [
      {
        label: "关闭",
        value: 0
      },
      {
        label: "开启",
        value: 1
      }
    ]
  }
];
const visible = ref(false);
const values = ref<FieldValues>({});
const confirmLoading = ref(false);
function editClick(row) {
  console.log(
    "%crow===编辑>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    row
  );
  values.value = {
    userId: row.id,
    money: row.money,
    score: row.score,
    level: row.level,
    starrating: row.starrating,
    status: row.status,
    levelAdmin: row.level_admin,
    showLevel: row.showLevel,
    jtsfkg: row.jtsfkg
  };
  visible.value = true;
}

const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  console.log("updatedValues", updatedValues);

  confirmLoading.value = true;
  try {
    const res = await setUser(updatedValues);
    visible.value = false;
    confirmLoading.value = false;
    formRef.value?.formInstance?.resetFields();
    ElMessage.success("编辑成功");
    loadData();
  } catch (error) {
    confirmLoading.value = false;
    console.log(error, "error");
  }
};

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset");
  onKeywordChange(value);
};

const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (
    target.prop == "keyWord" ||
    target.prop == "pId" ||
    target.prop == "weight"
  ) {
    return;
  }
  onKeywordChange(value);
};

const changePwd = (item: any, type: string) => {
  addDialog({
    title: type == "pwd" ? "修改登录密码" : "修改支付密码",
    width: "30%",
    draggable: true,
    sureBtnLoading: true,
    contentRenderer: () => dialogForms,
    props: {
      formInline: {
        type,
        mobile: item.account
      }
    },
    beforeSure: async (done, { options, index, closeLoading }) => {
      const { formInline } = options.props;
      const type = formInline.type;
      const password = formInline.password;
      if (type == "pwd") {
        if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(password)) {
          ElMessage.error("密码必须包含数字和字母且至少8位");
          closeLoading();
          return;
        }
      } else {
        if (!/^\d{6}$/.test(password)) {
          ElMessage.error("密码必须是纯数字6位");
          closeLoading();
          return;
        }
      }

      try {
        const res = await setUserPwd(formInline);
        closeLoading();
        done();
        ElMessage.success(
          type == "pwd" ? "登录密码修改成功" : "支付密码修改成功"
        );
      } catch (error) {
        closeLoading();
      }
    }
  });
};

const formRef = ref();
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>用户管理</h3>
        </template>
        <PlusSearch
          v-model="searchValues"
          :defaultValues="defaultSearchState"
          class="mt-5"
          :columns="searchColumns"
          :hasUnfold="false"
          @reset="handleReset"
          @search="handleSearch"
          @change="handleChange"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      :adaptive="false"
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
      :pagination="pagination"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #operation="{ row }">
        <div :class="['flex gap-1', isMobile ? 'flex-col' : 'flex-row']">
          <el-button
            v-if="power.setHhr"
            type="info"
            size="small"
            @click="setHhr(row)"
          >
            设置合伙人(test)
          </el-button>
          <el-button
            v-if="power.info"
            type="info"
            size="small"
            @click="detailClick(row)"
          >
            详情
          </el-button>
          <el-button
            v-if="false"
            type="primary"
            size="small"
            @click="editClick(row)"
            >编辑</el-button
          >
          <el-button
            v-if="power.loginPwd"
            type="danger"
            size="small"
            @click="changePwd(row, 'pwd')"
          >
            登录密码
          </el-button>
          <el-button
            v-if="power.payPwd"
            type="danger"
            size="small"
            @click="changePwd(row, 'pay')"
            >支付密码</el-button
          >
        </div>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      title="编辑用户信息"
      @confirm="handleSubmit"
    />
  </ElCard>
</template>

<style scoped></style>
